﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
namespace Admin.NET.Application;

/// <summary>
/// 销售订单服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public partial class SyssalesorderService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Syssalesorder> _syssalesorderRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public SyssalesorderService(SqlSugarRepository<Syssalesorder> syssalesorderRep, ISqlSugarClient sqlSugarClient)
    {
        _syssalesorderRep = syssalesorderRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询销售订单 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询销售订单")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<SyssalesorderOutput>> Page(PageSyssalesorderInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _syssalesorderRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.Code.Contains(input.Keyword) || u.CustomerName.Contains(input.Keyword) || u.ContactPerson.Contains(input.Keyword) || u.ContactMethod.Contains(input.Keyword) || u.GoodsName.Contains(input.Keyword) || u.Remark.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Code), u => u.Code.Contains(input.Code.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerName), u => u.CustomerName.Contains(input.CustomerName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ContactPerson), u => u.ContactPerson.Contains(input.ContactPerson.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ContactMethod), u => u.ContactMethod.Contains(input.ContactMethod.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.GoodsName), u => u.GoodsName.Contains(input.GoodsName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(input.DocumentStatus.HasValue, u => u.DocumentStatus == input.DocumentStatus.Value)
            .WhereIF(input.SalesDateRange?.Length == 2, u => u.SalesDate >= input.SalesDateRange[0] && u.SalesDate <= input.SalesDateRange[1])
            .WhereIF(input.SalesDeptId != null, u => u.SalesDeptId == input.SalesDeptId)
            .WhereIF(input.SalesManagerId != null, u => u.SalesManagerId == input.SalesManagerId)
            .WhereIF(input.SalesQuantity != null, u => u.SalesQuantity == input.SalesQuantity)
            .WhereIF(input.DeleteTimeRange?.Length == 2, u => u.DeleteTime >= input.DeleteTimeRange[0] && u.DeleteTime <= input.DeleteTimeRange[1])
            .Select<SyssalesorderOutput>();
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取销售订单详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取销售订单详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Syssalesorder> Detail([FromQuery] QueryByIdSyssalesorderInput input)
    {
        return await _syssalesorderRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加销售订单 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加销售订单")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddSyssalesorderInput input)
    {
        var entity = input.Adapt<Syssalesorder>();
        return await _syssalesorderRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新销售订单 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新销售订单")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateSyssalesorderInput input)
    {
        var entity = input.Adapt<Syssalesorder>();
        await _syssalesorderRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除销售订单 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除销售订单")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteSyssalesorderInput input)
    {
        var entity = await _syssalesorderRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _syssalesorderRep.FakeDeleteAsync(entity);   //假删除
        //await _syssalesorderRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除销售订单 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除销售订单")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteSyssalesorderInput> input)
    {
        var exp = Expressionable.Create<Syssalesorder>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _syssalesorderRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _syssalesorderRep.FakeDeleteAsync(list);   //假删除
        //return await _syssalesorderRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 导出销售订单记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出销售订单记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageSyssalesorderInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportSyssalesorderOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "销售订单导出记录");
    }
    
    /// <summary>
    /// 下载销售订单数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载销售订单数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportSyssalesorderOutput>(), "销售订单导入模板");
    }
    
    private static readonly object _syssalesorderImportLock = new object();
    /// <summary>
    /// 导入销售订单记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入销售订单记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (_syssalesorderImportLock)
        {
            var stream = ExcelHelper.ImportData<ImportSyssalesorderInput, Syssalesorder>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.DocumentStatus == null){
                            x.Error = "单据状态不能为空";
                            return false;
                        }
                        if (x.SalesQuantity == null){
                            x.Error = "销售数量不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<Syssalesorder>>();
                    
                    var storageable = _syssalesorderRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Code), "销售单号不能为空")
                        .SplitError(it => it.Item.Code?.Length > 64, "销售单号长度不能超过64个字符")
                        .SplitError(it => it.Item.CustomerName?.Length > 128, "客户名称长度不能超过128个字符")
                        .SplitError(it => it.Item.ContactPerson?.Length > 64, "联系人长度不能超过64个字符")
                        .SplitError(it => it.Item.ContactMethod?.Length > 32, "联系方式长度不能超过32个字符")
                        .SplitError(it => it.Item.GoodsName?.Length > 512, "销售货品长度不能超过512个字符")
                        .SplitError(it => it.Item.Remark?.Length > 512, "备注长度不能超过512个字符")
                        .SplitInsert(_=> true) // 没有设置唯一键代表插入所有数据
                        .ToStorage();
                    
                    storageable.AsInsertable.ExecuteCommand();// 不存在插入
                    storageable.AsUpdateable.UpdateColumns(it => new
                    {
                        it.Code,
                        it.DocumentStatus,
                        it.SalesDate,
                        it.CustomerName,
                        it.ContactPerson,
                        it.ContactMethod,
                        it.SalesDeptId,
                        it.SalesManagerId,
                        it.SalesQuantity,
                        it.SalesAmount,
                        it.GoodsName,
                        it.Remark,
                        it.DeleteTime,
                    }).ExecuteCommand();// 存在更新
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
